<?php
use think\Db;
use Aliyun\Core\Config;  
use Aliyun\Core\Profile\DefaultProfile;  
use Aliyun\Core\DefaultAcsClient;  
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use think\Env;


function exportHtmlTableToExcel($html, $filename = 'export.xlsx') {

        vendor("PHPExcel.PHPExcel");
        vendor("PHPExcel.PHPExcel.IOFactory");
    // 创建 PHPExcel 对象
	$html = mb_convert_encoding($html, "GB2312", "UTF-8");
    $objPHPExcel = new PHPExcel();
    $sheet = $objPHPExcel->getActiveSheet();
   
    // 解析 HTML 表格
    $dom = new DOMDocument();
    @$dom->loadHTML($html);
    $tables = $dom->getElementsByTagName('table');
   
    if ($tables->length > 0) {
        $table = $tables->item(0);
        $rows = $table->getElementsByTagName('tr');
        // dump($rows);die;
        $rowIndex = 1;
        foreach ($rows as $row) {
            $cols = $row->getElementsByTagName('td');
            $colIndex = 0;
            
            // 处理表头 (th)
            $headers = $row->getElementsByTagName('th');
            if ($headers->length > 0) {
                foreach ($headers as $header) {
                    $sheet->setCellValueByColumnAndRow($colIndex, $rowIndex, trim($header->nodeValue));
                    $colIndex++;
                }
            } 
            // 处理数据行 (td)
            else {
                foreach ($cols as $col) {
                    $sheet->setCellValueByColumnAndRow($colIndex, $rowIndex, trim($col->nodeValue));
                    $colIndex++;
                }
            }
            $rowIndex++;
        }
    }
    
    // 设置 HTTP 头
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="'.$filename.'"');
    header('Cache-Control: max-age=0');
    
    // 输出文件
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

    $objWriter->save('./1.xlsx');
    exit;
}
/**
 * 创建服务对象
 * @param string $name  服务名称
 * @param null $modelName 模型名称
 * @return \app\common\service\Service
 */
function service($name)
{
    if (empty($name)) {
        return new \app\common\service\Service();
    } else {
        $request = \think\Request::instance();
        $module = $request->module();
        $class = "\\app\\" . $module . "\\service\\" . $name;
        if (class_exists($class)) {
            return new $class($name);
        } else {
            //找不到自定义 调用原生的
            return new \app\common\service\Service($name);
        }
    }
}



function subtext($text, $length)
{
    if (mb_strlen($text, 'utf8') > $length) {
        return mb_substr($text, 0, $length, 'utf8') . '...';
    } else {
        return $text;
    }
}


function search_plan_like($array, $substring)
{
	
	foreach ($array as $key=>$item) {
		if (strpos($key, $substring) !== false) {
			return $item;
		}
	}
	return '-';
}

function search_plan_like_major($plan_list, $kw,$school_uuid)
{
	
	//foreach ($plan_list as $key=>$item) {
	//	if ($item['school_uuid']==$school_uuid && strpos($item['college_major_name'], $kw) !== false) {
	//		return $item['enrollment_numbers'];
	//	}
	//}
	foreach ($plan_list as $key=>$item) {
		if ($item['college_major_name'] == $kw) {
			return $item['enrollment_numbers'];
		}
	}
	foreach ($plan_list as $key=>$item) {
		if (strpos($item['college_major_name'], $kw) !== false) {
			return $item['enrollment_numbers'];
		}
	}
	
	if (strpos($kw, '（') !== false) {
		$result = substr($kw, 0, strpos($kw, '（'));
	}elseif (strpos($kw, '(') !== false) {
		$result = substr($kw, 0, strpos($kw, '（'));
	}
	if (!empty($result)) {
		foreach ($plan_list as $key=>$item) {
			if (strpos($item['college_major_name'], $result) !== false) {
				return $item['enrollment_numbers'];
			}
		}
	}
	
	return '-';
}

function search_major_like($major_list, $major_name)
{
	
	foreach ($major_list as $key=>$item) {
		if ($item['major_name'] == $major_name) {
			return $item;
		}
	}
	foreach ($major_list as $key=>$item) {
		if (strpos($item['major_name'], $major_name) !== false) {
			return $item;
		}
	}
	
	 
	if (strpos($major_name, '（') !== false) {
		$result = substr($major_name, 0, strpos($major_name, '（'));
	}elseif (strpos($major_name, '(') !== false) {
		$result = substr($major_name, 0, strpos($major_name, '（'));
	}
	if (!empty($result)) {
		foreach ($major_list as $key=>$item) {
			if (strpos($item['major_name'], $result) !== false) {
				return $item;
			}
		}
	}
	return ['score_min'=>'-','weici_min'=>'-','dengxiao_weicha'=>'-','linecha'=>'-','plan_nums'=>'-'];
}

function filter_subject_group($string)
{
	
	$string = str_replace("（","(",$string);
	$string = str_replace("）",")",$string);
	return $string;
}


//专业去重
function array_unique_two($array)
{
	
	$result = [];
	foreach ($array as $row) {
		$flag = true;
		foreach ($result as $item) {
			/*if ($item['major_name'] == $row['major_name'] && $item['major_code'] == $row['major_code']) {
				$flag = false;
				break;
			}*/
			/*if ($item['major_name'] == $row['major_name'] && $item['weici_min'] == $row['weici_min']) {
				$flag = false;
				break;
			}
			
			if (!empty($item['major_code']) && $item['major_code'] == $row['major_code'] && $item['weici_min'] == $row['weici_min']) {
				$flag = false;
				break;
			}*/
			if ($item['major_name'] == $row['major_name']) {
				$flag = false;
				break;
			}
		}
		if ($flag) {
			$result[] = $row;
		}
	}
	return $result;
}
/**
 * 打印日志
 * @param $key
 * @param $content
 * @param int $type
 * @return array
 */
function log_out($key, $content, $type = 1)
{
    $logService = new \app\common\service\Log();
    return $logService->log($key, $content, $type);
}

/**
 * 调试日志
 * @param $key
 * @param $content
 * @return array
 */
function log_debug($key, $content)
{
    return log_out($key, $content, 2);
}

/**
 * 错误日志
 * @param $key
 * @param $content
 * @return array
 */
function log_error($key, $content)
{
    return log_out($key, $content, 3);
}

/**
 * 信息日志
 * @param $key
 * @param $content
 * @return array
 */
function log_info($key, $content)
{
    return log_out($key, $content, 1);
}


function setLog($logname,$data){

    $log_parh =  ROOT_PATH.'public/log/' .$logname . '/';

    $file_name = date('Ym') . ".log";
    if(is_array($data)){
        $text='【result】='.var_export($data,true).';';
    }else{
        $text = '【 动作 】：'.$data;
    }
    if(!is_dir($log_parh)){
        $flag = mkdir($log_parh,0777,true);
    }

    $contents = '['.date('Y-m-d H:i:s',time()).']'.'---'.PHP_EOL.$text;
    file_put_contents($log_parh.$file_name,$contents.PHP_EOL, FILE_APPEND);
    return;
}

/**
 * curl抓取数据
 * @param $url  地址
 * @param null $data post提交的数据
 * @return mixed
 */
function http_request($url, $data = null)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

/**
 * 从省份城市中查找出省份 如广东广州  找出的结果为广东
 * @param $city
 * @return bool|mixed 找不到返回false
 */
function getProvinceCity($provinceCity)
{
    $provinces = array('北京', '广东', '广西', '天津', '湖北', '河南', '河北', '江苏', '浙江', '江西', '四川', '贵州', '安徽', '山东', '山西', '辽宁', '吉林', '福建', '重庆', '青海', '云南', '海南', '陕西', '甘肃', '黑龙江', '内蒙古', '新疆', '西藏', '上海', '宁夏', '湖南');
    foreach ($provinces as $province) {
        $pos = strpos($provinceCity, $province);
        if (is_numeric($pos) && $pos == 0) {
            $city = substr($provinceCity, strlen($province));
            return ['province' => $province, 'city' => $city];
        }
    }
    return false;
}

/**
 *
 * @param string $uri uri:模块名/控制器/操作
 * @param $data 如果为string,则采用get请求，否则采用post
 * @return mixed
 */
function http_request_center($uri = 'api/index/index', $data = '')
{
    $url = config("cmp_center_url") . $uri . '?appid=' . config("appid") . '&token=' . config("token");
    if (is_string($data)) {
        $url = $url . '&' . $data;
        $result = http_request($url);
    } else {
        $result = http_request($url, $data);
    }
    $arr = json_decode($result, true);
    if ($arr == null) {
        log_debug("请求控制中心失败", $result);
        return false;
    } else
        return $arr;
}


function getMemberRealname($user_id)
{	
	if(empty($user_id)){
		return '';
	}
	return Db::name('member')->where('id',$user_id)->value('realname');
    
}

function getMemberPhone($user_id)
{	
	if(empty($user_id)){
		return '';
	}
	return Db::name('member')->where('id',$user_id)->value('phone');
    
}

/**
 * 请求参数过滤
 * @param string $type
 * @return mixed
 */
function input_except($type = 'param')
{
    return \think\Request::instance()->except(['apptoken', 'membertoken'], $type);
}

/**
 * 获取get请求参数
 * @param null $name
 * @return mixed
 */
function get($name = null, $default = null)
{
    $get = input_except('get');
    if (isset($name)) {
        if (isset($default)) {
            if (isset($get[$name])) {
                return $get[$name];
            } else {
                return $default;
            }
        } else
            return $get[$name];
    } else {
        return $get;
    }
}

/**
 * 获取post请求参数
 * @param null $name
 * @return mixed
 */
function post($name = null, $default = null)
{
    $post = input_except('post');
    if (isset($name)) {
        if (isset($default)) {
            if (isset($post[$name])) {
                return $post[$name];
            } else {
                return $default;
            }
        } else
            return $post[$name];
    } else {
        return $post;
    }
}

/**
 * 获取param请求参数
 * @param null $name
 * @return mixed
 */
function param($name = null, $default = null)
{
    $param = input_except('param');
    if (isset($name)) {
        if (isset($default)) {
            if (isset($param[$name])) {
                return $param[$name];
            } else {
                return $default;
            }
        } else
            return $param[$name];
    } else {
        return $param;
    }
}


/**
 * 获取输出结果
 * @param int $code 为整数：自定义返回数据，为字符串，返回api_code定义数据，为数组，直接返回定义好的格式
 * @param string $msg
 * @param array $data
 * @return \think\Response
 */
function show($code = 0, $msg = '', $data = array())
{
    $responceCode = config("api_code");
    $result = [];
    if (is_int($code)) {//默认为自定义消息响应
        $result['code'] = $code;
        $result['msg'] = $msg;
        $result['data'] = $data;
    } else if (is_string($code)) {//默认为api_code中的消息响应
        if (isset($responceCode[$code])) {
            $result = $responceCode[$code];
            $result['data'] = $data;
        } else {
            $result['code'] = 0;
            $result['msg'] = $code;//把未知错误信息作为提示
            $result['data'] = $data;
        }

    } else if (is_array($code)) {//数组，可能是api_code消息,也有可能是自定义消息
//            判断提示消息是否来自api_code
        $result = $code;
        if (isset($responceCode[$code['msg']])) {

            $tempcode = $responceCode[$code['msg']];
            if (empty($tempcode)) {
                $tempcode = $responceCode['unknow_error'];
            }
            if ($code['code'] == 1) {//成功的代码只有一个，只利用其提醒消息msg
                $result['msg'] = $tempcode['msg'];
            } else {
                $result['msg'] = $tempcode['msg'];
                $result['code'] = $tempcode['code'];
            }
        }
        if (!empty($result['data']) && is_array($result['data'])) {
            $data = array_merge($result['data'], $data);
            $result['data'] = $data;
        }
    }
    return $result;
}

/**
 * 获取成功响应
 * @param array $data
 * @return mixed
 */
function success($msg = 'success', $data = array())
{
    $responceCode = config("api_code");
    if (is_string($msg)) {
        if (isset($responceCode[$msg])) {
            return show($msg, '', $data);
        } else {
            return show(1, $msg, $data);
        }
    } else if (is_array($msg)) {
        return show('success', '', $msg);
    }
}

/**
 * 获取错误响应
 * @param array $data
 * @return mixed
 */
function error($msg = 'error', $data = array())
{
    $responceCode = config("api_code");
    if (is_string($msg)) {
        if (isset($responceCode[$msg])) {
            return show($msg, '', $data);
        } else {
            return show(0, $msg, $data);
        }
    } else if (is_array($msg)) {
        return show('error', '', $msg);
    }
}

/**
 * 获取当前url
 * @return string
 */
function get_current_url()
{
    $url='';
    if (isset($_SERVER ['HTTP_HOST']) && $_SERVER['PHP_SELF'])
        $url = "http://" . $_SERVER ['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    return $url;
}


/**
 * 字符串截取，支持中文和其他编码
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true) {
	if (function_exists("mb_substr"))
		$slice = mb_substr($str, $start, $length, $charset);
	elseif (function_exists('iconv_substr')) {
		$slice = iconv_substr($str, $start, $length, $charset);
		if (false === $slice) {
			$slice = '';
		}
	} else {
		$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
		$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
		$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
		$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
		preg_match_all($re[$charset], $str, $match);
		$slice = join("", array_slice($match[0], $start, $length));
	}
	return $suffix ? $slice . '...' : $slice;
}



/**
 * 读取配置
 * @return array 
 */
function load_config(){
    $list = Db::name('config')->select();
    $config = [];
    foreach ($list as $k => $v) {
        $config[trim($v['name'])]=$v['value'];
    }

    return $config;
}


/**
* 验证手机号是否正确
* @author honfei
* @param number $mobile
*/
function isMobile($mobile) {
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
}


/** 
 * 阿里云云通信发送短息 
 * @param string $mobile    接收手机号 
 * @param string $tplCode   短信模板ID
 * @param array  $tplParam  短信内容
 * @return array 
 */  
function sendMsg($mobile,$tplCode,$tplParam){  
    if( empty($mobile) || empty($tplCode) ) return array('Message'=>'缺少参数','Code'=>'Error');  
    if(!isMobile($mobile)) return array('Message'=>'无效的手机号','Code'=>'Error');  
      
    require_once '../extend/aliyunsms/vendor/autoload.php';  
    Config::load();             //加载区域结点配置   
    $accessKeyId = config('alisms_appkey');  
    $accessKeySecret = config('alisms_appsecret');  
    if( empty($accessKeyId) || empty($accessKeySecret) ) return array('Message'=>'请先在后台配置appkey和appsecret','Code'=>'Error'); 
    $templateParam = $tplParam; //模板变量替换  
    //$signName = (empty(config('alisms_signname'))?'阿里大于测试专用':config('alisms_signname'));  
	$signName = config('alisms_signname');  
    //短信模板ID 
    $templateCode = $tplCode;   
    //短信API产品名（短信产品名固定，无需修改）  
    $product = "Dysmsapi";  
    //短信API产品域名（接口地址固定，无需修改）  
    $domain = "dysmsapi.aliyuncs.com";  
    //暂时不支持多Region（目前仅支持cn-hangzhou请勿修改）  
    $region = "cn-hangzhou";     
    // 初始化用户Profile实例  
    $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);  
    // 增加服务结点  
    DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);  
    // 初始化AcsClient用于发起请求  
    $acsClient= new DefaultAcsClient($profile);  
    // 初始化SendSmsRequest实例用于设置发送短信的参数  
    $request = new SendSmsRequest();  
    // 必填，设置雉短信接收号码  
    $request->setPhoneNumbers($mobile);  
    // 必填，设置签名名称  
    $request->setSignName($signName);  
    // 必填，设置模板CODE  
    $request->setTemplateCode($templateCode);  
    // 可选，设置模板参数     
    if($templateParam) {
        $request->setTemplateParam(json_encode($templateParam));
    }
    //发起访问请求  
    $acsResponse = $acsClient->getAcsResponse($request);   
    //返回请求结果  
    $result = json_decode(json_encode($acsResponse),true); 

    return $result;  
}  



//生成网址的二维码 返回图片地址
function Qrcode($token, $url, $size = 8){ 
    $md5 = md5($token);
    $dir = date('Ymd'). '/' . substr($md5, 0, 10) . '/';
    $patch = 'qrcode/' . $dir;
    if (!file_exists($patch)){
        mkdir($patch, 0755, true);
    }
    $file = 'qrcode/' . $dir . $md5 . '.png';
    $fileName =  $file;
    if (!file_exists($fileName)) {

        $level = 'L';
        $data = $url;
        \org\QRcode::png($data, $fileName, $level, $size, 2, true);
    }
    return $file;
}



/**
 * 循环删除目录和文件
 * @param string $dir_name
 * @return bool
 */
function delete_dir_file($dir_name) {
    $result = false;
    if(is_dir($dir_name)){
        if ($handle = opendir($dir_name)) {
            while (false !== ($item = readdir($handle))) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . DS . $item)) {
                        delete_dir_file($dir_name . DS . $item);
                    } else {
                        unlink($dir_name . DS . $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name)) {
                $result = true;
            }
        }
    }

    return $result;
}



//时间格式化1
function formatTime($time) {
    $now_time = time();
    $t = $now_time - $time;
    $mon = (int) ($t / (86400 * 30));
    if ($mon >= 1) {
        return '一个月前';
    }
    $day = (int) ($t / 86400);
    if ($day >= 1) {
        return $day . '天前';
    }
    $h = (int) ($t / 3600);
    if ($h >= 1) {
        return $h . '小时前';
    }
    $min = (int) ($t / 60);
    if ($min >= 1) {
        return $min . '分钟前';
    }
    return '刚刚';
}


//时间格式化2
function pincheTime($time) {
     $today  =  strtotime(date('Y-m-d')); //今天零点
      $here   =  (int)(($time - $today)/86400) ; 
      if($here==1){
          return '明天';  
      }
      if($here==2) {
          return '后天';  
      }
      if($here>=3 && $here<7){
          return $here.'天后';  
      }
      if($here>=7 && $here<30){
          return '一周后';  
      }
      if($here>=30 && $here<365){
          return '一个月后';  
      }
      if($here>=365){
          $r = (int)($here/365).'年后'; 
          return   $r;
      }
     return '今天';
}


function getRandomString($len, $chars=null){
    if (is_null($chars)){
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    }  
    mt_srand(10000000*(double)microtime());
    for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
        $str .= $chars[mt_rand(0, $lc)];  
    }
    return $str;
}


function random_str($length){
    //生成一个包含 大写英文字母, 小写英文字母, 数字 的数组
    $arr = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
 
    $str = '';
    $arr_len = count($arr);
    for ($i = 0; $i < $length; $i++)
    {
        $rand = mt_rand(0, $arr_len-1);
        $str.=$arr[$rand];
    }
 
    return $str;
}



/**
 * 计算两点地理坐标之间的距离
 * @param  float $longitude1 起点经度
 * @param  float $latitude1  起点纬度
 * @param  float $longitude2 终点经度
 * @param  float $latitude2  终点纬度
 * @param  Int     $unit       单位 1:米 2:公里
 * @param  Int     $decimal    精度 保留小数位数
 * @return mixed
 */
function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=1, $decimal=2){

    $EARTH_RADIUS = 6370.996; // 地球半径系数
    $PI = 3.1415926;

    $radLat1 = $latitude1 * $PI / 180.0;
    $radLat2 = $latitude2 * $PI / 180.0;

    $radLng1 = $longitude1 * $PI / 180.0;
    $radLng2 = $longitude2 * $PI /180.0;

    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;

    $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
    $distance = $distance * $EARTH_RADIUS * 1000;

    if($unit==2){
        $distance = $distance / 1000;
    }

    return round($distance, $decimal);
}


function getAreaName($id)
{
    return  Db::name('region')->where('id',$id)->value('name');
}


function getTimeDis($time_limit)
{
   $da = date('Y-m-d',time());
   $arr = explode('-',$time_limit);
   $time1 = strtotime(trim($da.' '.trim($arr[0]).':00'));
   $time2 = strtotime(trim($da.' '.trim($arr[1]).':00'));
   if($time1 > $time2) $time2 = $time2 + 24*3600;
   return [$time1,$time2];
}



//获取当前时间需要分时推荐的id
function getTimeId()
{
    $da = date('Y-m-d',time());
    $info = db('time_recommend')->where('is_show',1)->select();
    $tt = [];
    if($info)
    {
        foreach ($info as $kk => $vv)
        {
            $arr = explode('-',$vv['time_limit']);
            $time1 = strtotime(trim($da.' '.$arr[0].':00'));
            $time2 = strtotime(trim($da.' '.$arr[1].':00'));
            if($time1 > $time2) $time2 = $time2 + 24*3600;
            if(time() >= $time1 && time()<= $time2)
            {
                $tt['id'] = $vv['id'];
                $tt['name'] = $vv['name'];
                break;
            }
        }
    }
    return $tt;
}


//根据减少的数据计算消耗度
function getLess($heat)
{
    $dd = ['less_rice'=>0,'less_mile'=>0,'less_apple'=>0];
    $dd['less_rice'] = intval($heat/config('kl_rice'));
    $dd['less_mile'] = intval($heat/config('kl_mile'));
    $dd['less_apple'] = intval($heat/config('kl_apple'));
    return $dd;
}

function get_order_sn($exp='')
{
    $result = $exp.str_pad(mt_rand(100, 999), 3, '0', STR_PAD_LEFT).date('YmdHis').str_pad(mt_rand(100, 999), 3, '0', STR_PAD_LEFT);
    return $result;
}


/**
 * Generate a signature.
 *
 * @param array  $attributes
 * @param string $key
 * @param string $encryptMethod
 *
 * @return string
 */
function generate_sign(array $attributes, $key, $encryptMethod = 'md5')
{
    ksort($attributes);

    $attributes['key'] = $key;

    return strtoupper(call_user_func_array($encryptMethod, [urldecode(http_build_query($attributes))]));
}


//达达接口参数签
function checkSign($data,$app_secret)
{
    // 1. 对加密数组进行字典排序 防止因为参数顺序不一致而导致下面拼接加密不同
    ksort($data);
    // 2. 将Key和Value拼接
    $str = "";
    foreach ($data as $k => $v) {
        if(is_array($v)) $v = json_encode($v);
        $str.= $k.$v;
    }
    //3. 通过md5加密并转化为大写
    $reStr=$app_secret.$str.$app_secret;
    $sign = strtoupper(md5($reStr));
    //4. 大写获得签名
    return $sign;
}

//获取所有子节点id
function getAllMajorChildId($id,$data=[]){
    $pids = DB::name('major')->where('cate_pid',$id)->column('id');
    if(count($pids)>0){
        foreach($pids as $v){
            $data[] = $v;
            $data = getAllMajorChildId($v,$data); //注意写$data 返回给上级
        }
    }
    if(count($data)>0){
        return $data;
    }else{
        return false;
    }
}
function getAllAreaChildId($id,$data=[]){
    $pids = DB::name('area')->where('pid',$id)->column('id');
    if(count($pids)>0){
        foreach($pids as $v){
            $data[] = $v;
            $data = getAllAreaChildId($v,$data); //注意写$data 返回给上级
        }
    }
    if(count($data)>0){
        return $data;
    }else{
        return false;
    }
}

function array_sort($array,$keys,$type='asc'){
    //$array为要排序的数组,$keys为要用来排序的键名,$type默认为升序排序
    $keysvalue = $new_array = array();
    foreach ($array as $k=>$v){
        $keysvalue[$k] = $v[$keys];
    }
    if($type == 'asc'){
        asort($keysvalue);
    }else{
        arsort($keysvalue);
    }
    reset($keysvalue);
    foreach ($keysvalue as $k=>$v){
        $new_array[$k] = $array[$k];
    }
    return $new_array;
}